package com.google.code.jmarias.server.tcp;

import com.google.code.jmarias.common.action.SignedAction;
import java.io.IOException;
import java.net.ServerSocket;
import java.util.concurrent.BlockingQueue;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Vlakno, ktere posloucha na urcenem TCP portu a pripojuje nove klienty.
 *
 * @TODO Az bude rozhrani vice, zjistit, co vsechno by se dalo vyjmout do abstraktni
 * nadtridy AbstractServerConnector.
 *
 * Neni potreba, aby byla thread-safe.
 *
 * @author Ondrej Michal
 */
public class SocketServerConnector extends Thread {

    private static final int PORT = 4444;

    private static Log log = LogFactory.getLog(SocketServerConnector.class);

    BlockingQueue<SignedAction> clientToServerActions;

    public SocketServerConnector(BlockingQueue<SignedAction> clientToServerActions) {
        this.clientToServerActions = clientToServerActions;
    }
    
    @Override
    public void run() {
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(PORT);
            log.info("Server spusten a nasloucha na portu " + PORT);


            while (true) {
                new SocketClient(serverSocket.accept(), clientToServerActions).start();
            }

        } catch (IOException ex) {
            log.error("Vlakno komunikujici s klienty pres tcp socket selhalo.", ex);
        } finally {
            if (serverSocket != null) {
                try {
                    serverSocket.close();
                } catch (IOException ex) {
                }
            }
        }
    }
}
